/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-11-08
 * Time: 19:02
 */
public class SharedStack {
    private int[] stack;
    private int top1;
    private int top2;
    private int size;

    public SharedStack(int size) {
        this.size = size;
        this.stack = new int[size];
        this.top1 = -1;
        this.top2 = size;
    }

    // S1入栈
    public void push1(int value) {
        if (top1 + 1 < top2) {
            top1++;
            stack[top1] = value;
        } else {
            throw new StackOverflowError("Stack1 is full");
        }
    }

    public int pop1() {
        if (top1 >= 0) {
            int value = stack[top1];
            top1--;
            return value;
        } else {
            System.out.println("Stack1 is empty");
            return 0;
        }
    }


    public void push2(int value) {
        if (top2 - 1 > top1) {
            top2--;
            stack[top2] = value;
        } else {
            throw new StackOverflowError("Stack2 is full");
        }
    }


    public int pop2() {
        if (top2 < size) {
            int value = stack[top2];
            top2++;
            return value;
        } else {
            System.out.println("Stack1 is empty");
            return 0;
        }
    }


    public boolean isEmpty1() {
        return top1 == -1;
    }


    public boolean isEmpty2() {
        return top2 == size;
    }


    public int peek1() {
        if (!isEmpty1()) {
            return stack[top1];
        } else {
            System.out.println("Stack1 is empty");
            return 0;
        }
    }


    public int peek2() {
        if (!isEmpty2()) {
            return stack[top2 - 1];
        } else {
            System.out.println("Stack1 is empty");
            return 0;
        }
    }
}